package com.wangyadong.hobby.common.utils;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;


public class UniqueIDUtil implements InitializingBean {

    private static final Logger logger = Logger.getLogger(UniqueIDUtil.class);

    public static IdWorker w = null;

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    public static void init() {
        long workerId = Long.valueOf(ConfigurableApplitionUtil.getProperty("workerId"));
        long datacenterId = Long.valueOf(ConfigurableApplitionUtil.getProperty("datacenterId"));
        if (workerId <= 0) {
            logger.error("server id error, please check config file!");
            System.exit(-1);
        }
        w = new IdWorker(workerId, datacenterId);
    }

    public static void init(long workerId, long datacenterId) {

        if (workerId <= 0) {
            logger.error("server id error, please check config file!");
            System.exit(-1);
        }
        w = new IdWorker(workerId, datacenterId);
    }


    /**
     * 获取主键ID
     *
     * @return
     * @throws Exception
     */
    public static synchronized long getUniqueID() throws Exception {
        return w.nextId();
    }
}
